package com.hoas.distributedlock.spring;

import com.hoas.distributedlock.strategy.redis.RedisLock;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.Protocol;
import redis.clients.util.SafeEncoder;

public class SpringRedisLock extends RedisLock {
    public SpringRedisLock(RedisTemplate redisTemplate) {
        super(null);
        this.redisTemplate = redisTemplate;

    }

    private RedisTemplate redisTemplate;

    @Override
    protected boolean redis_setnx(final String key, final String value, final long exptime) {
        Boolean b = (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {

            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
                RedisSerializer keySerializer = redisTemplate.getKeySerializer();
                Object obj = connection.execute("set", keySerializer.serialize(key),
                        valueSerializer.serialize(value),
                        SafeEncoder.encode("NX"),
                        SafeEncoder.encode("EX"),
                        Protocol.toByteArray(exptime));
                return obj != null;
            }
        });
        return b;
    }

    @Override
    protected void redis_del(String... keys) {
        redisTemplate.delete(keys);
    }
}
